import _createForOfIteratorHelper from "@babel/runtime/helpers/esm/createForOfIteratorHelper";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _uniq from "lodash/uniq";
import _sortBy from "lodash/sortBy";
import _isEmpty from "lodash/isEmpty";
import _isArray from "lodash/isArray";
var _excluded = ["page", "sort"],
    _excluded2 = ["$form"];

/**
 * 其他相关
 * @date: 2019-12-25

 */
import { notification } from 'antd';
import { GLOBAL_PAGE_SIZE, PAGE_SIZE_OPTIONS } from "../constants";
import intl from "../intl";
import { getCurrentOrganizationId, isTenantRoleLevel } from "./user";
export function isPromise(obj) {
  return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
}
/**
 * tableScrollWidth - 计算滚动表格的宽度
 * 如果 fixWidth 不传或者为0, 会将没有设置宽度的列 宽度假设为 200
 * @param {array} columns - 表格列
 * @param {number} fixWidth - 不固定宽度列需要补充的宽度
 * @return {number} - 返回计算过的 x 值
 */

export function tableScrollWidth() {
  var columns = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  var fixWidth = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  var fillFixWidthCount = 0;
  var total = columns.reduce(function (prev, current) {
    if (current.width) {
      return prev + current.width;
    }

    fillFixWidthCount += 1;
    return prev;
  }, 0);

  if (fixWidth) {
    return total + fixWidth + 1;
  }

  return total + fillFixWidthCount * 200 + 1;
}
/**
 * 过滤掉对象值为 undefined 和 空字符串 和 空数组 的属性
 * @param {Object} obj
 * @returns {Object} 过滤后的查询参数
 */

export function filterNullValueObject(obj) {
  var result = {};

  if (obj && Object.keys(obj).length >= 1) {
    Object.keys(obj).forEach(function (key) {
      if (key && obj[key] !== undefined && obj[key] !== '' && obj[key] !== null) {
        // 如果查询的条件不为空
        if (_isArray(obj[key]) && obj[key].length === 0) {
          return;
        }

        result[key] = obj[key];
      }
    });
  }

  return result; // 返回查询条件
}
/**
 * 解析查询参数
 * @param {Object} params
 */

export function parseParameter() {
  var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var _params$page = params.page,
      page = _params$page === void 0 ? {
    current: 1,
    pageSize: 10
  } : _params$page,
      _params$sort = params.sort,
      sort = _params$sort === void 0 ? {} : _params$sort,
      body = params.body;

  if (sort.order === 'ascend') {
    sort.order = 'asc';
  }

  if (sort.order === 'descend') {
    sort.order = 'desc';
  }

  var sortObj = {};

  if (!_isEmpty(sort)) {
    sortObj.sort = "".concat(sort.field, ",").concat(sort.order);
  }

  return _objectSpread(_objectSpread({
    page: page.current - 1,
    size: page.pageSize
  }, body), sortObj);
}
/**
 * 解析查询参数
 * @param {Object} params
 * @returns {Object} 解析后的查询参数
 */

export function parseParameters() {
  var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

  var _params$page2 = params.page,
      page = _params$page2 === void 0 ? {} : _params$page2,
      _params$sort2 = params.sort,
      sort = _params$sort2 === void 0 ? {} : _params$sort2,
      others = _objectWithoutProperties(params, _excluded);

  var _page$current = page.current,
      current = _page$current === void 0 ? 1 : _page$current,
      _page$pageSize = page.pageSize,
      pageSize = _page$pageSize === void 0 ? GLOBAL_PAGE_SIZE : _page$pageSize;

  if (sort.order === 'ascend') {
    sort.order = 'asc';
  }

  if (sort.order === 'descend') {
    sort.order = 'desc';
  }

  var sortObj = {};

  if (!_isEmpty(sort)) {
    sortObj.sort = "".concat(sort.field, ",").concat(sort.order);
  }

  var size = pageSize;

  var sourceSize = _toConsumableArray(PAGE_SIZE_OPTIONS);

  if (!sourceSize.includes("".concat(pageSize))) {
    var sizes = _sortBy(_uniq([].concat(_toConsumableArray(sourceSize), ["".concat(pageSize)])), function (i) {
      return +i;
    });

    var index = sizes.findIndex(function (item) {
      return +item === pageSize;
    });
    size = +sizes[index];
  }

  return _objectSpread(_objectSpread({
    size: size,
    page: current - 1
  }, others), sortObj);
} // todo 调整消息返回

export function getResponse(response, errorCallback) {
  if (response && response.failed === true) {
    if (errorCallback) {
      errorCallback(response);
    } else {
      var msg = {
        message: intl.get('cpaas.common.notification.error').d('操作失败'),
        description: response.message
      };

      switch (response.type) {
        case 'info':
          notification.info(msg);
          break;

        case 'warn':
          notification.warning(msg);
          break;

        case 'error':
        default:
          notification.error(msg);
          break;
      }
    }
  } else {
    return response;
  }
}
/**
 * 捕获下载文件时的错误信息(表单下载)
 * @param {string} errorCode - 后端返回的错误类型
 * @param {string} msg - 自定义错误提示标题
 * @param {string} noticeType - 报错提示类型
 */

export function listenDownloadError() {
  var errorCode = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
  var msg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
  var noticeType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'error';
  // 监听表单下载错误时 postMessage 事件
  window.addEventListener('message', function (e) {
    var _e$data = e.data,
        type = _e$data.type,
        message = _e$data.message;

    if (type && type === errorCode) {
      notification[noticeType]({
        message: msg,
        description: message
      });
    }
  });
}
/**
 * getCodeMeaning - 在值集中根据value获取对应的meaning
 * @param {any} value - 值集中某对象的value
 * @param {Array<Object>} [code=[]] - 值集集合
 * @returns {string}
 */

export function getCodeMeaning(value) {
  var code = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  var result;

  if (value && !_isEmpty(code)) {
    var codeList = code.filter(function (n) {
      return n.value === value;
    });

    if (!_isEmpty(codeList)) {
      result = codeList[0].meaning;
    }
  }

  return result;
}
/**
 * 获取平台版本API
 */

export function getPlatformVersionApi(api) {
  var tenantId = getCurrentOrganizationId();
  var isTenantLevel = isTenantRoleLevel();
  return isTenantLevel ? "".concat(tenantId, "/").concat(api) : "".concat(api);
}
/**
 * 根据起始值生成响应的数组
 * @param {Number} start - 开始值
 * @param {Number} end - 结束值
 */

export function newArray(start, end) {
  var result = [];

  for (var i = start; i < end; i++) {
    result.push(i);
  }

  return result;
}
/**
 * 通过 ref 获取表单数据
 * this.filterFormRef = React.createRef();
 * <FilterForm wrappedComponentRef={this.filterFormRef} />
 * const data = getRefFormData(this.filterFormRef);
 * @param {React.RefObject<Form>} ref - 表单的 ref
 * @return {object}
 */

export function getRefFormData(ref) {
  if (ref.current) {
    var form = ref.current.props.form;
    return form.getFieldsValue();
  }

  return {};
}
export function getPlainNode(nodeList) {
  var parentPath = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
  var arr = [];
  nodeList.forEach(function (node) {
    var item = node;
    item.path = "".concat(parentPath, "/").concat(item.path || '').replace(/\/+/g, '/');
    item.exact = true;

    if (item.children && !item.component) {
      arr.push.apply(arr, _toConsumableArray(getPlainNode(item.children, item.path)));
    } else {
      if (item.children && item.component) {
        item.exact = false;
      }

      arr.push(item);
    }
  });
  return arr;
}
/**
 * 获取行内编辑表格中的 form
 * @param {array} dataSource - 表格数据源
 */

export function getEditTableForm(dataSource) {
  var formList = [];

  var fetchForm = function fetchForm(source, list) {
    if (Array.isArray(source)) {
      source.forEach(function (item) {
        if (item.$form) {
          list.push(item.$form);
        }

        if (item.children && Array.isArray(item.children)) {
          fetchForm(item.children, list);
        }
      });
    }
  };

  fetchForm(dataSource, formList);
  return formList;
}
/**
 * 获取行内编辑表格中的 form
 * @param {array} dataSource - 表格数据源
 * @param {array} filterList - 过滤新增操作中的属性字段，例如：['children', 'unitId']，默认过滤 $form
 * @param {object} scrollOptions - 配置form效验报错后的滚动行为，
 * - 默认是基于页面滚动，如果需要基于表格内滚动，
 * - 需要：{ container: document.querySelector('.ant-table-body') }，同时需要设置Y轴滚动
 * @param {string} treeChildrenAlias = 'children' - 指定树形结构行内编辑的子节点名称
 */

export function getEditTableData() {
  var dataSource = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  var filterList = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  var scrollOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var treeChildrenAlias = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'children';
  var paramsList = [];
  var errList = [];

  var fetchForm = function fetchForm(source, list) {
    if (Array.isArray(source)) {
      var _loop = function _loop(i) {
        if (source[i].$form && source[i]._status) {
          source[i].$form.validateFieldsAndScroll(_objectSpread({
            scroll: {
              allowHorizontalScroll: true
            }
          }, scrollOptions), function (err, values) {
            if (!err) {
              var _source$i = source[i],
                  $form = _source$i.$form,
                  otherProps = _objectWithoutProperties(_source$i, _excluded2);

              if (Array.isArray(filterList) && filterList.length > 0) {
                var _iterator = _createForOfIteratorHelper(filterList),
                    _step;

                try {
                  for (_iterator.s(); !(_step = _iterator.n()).done;) {
                    var name = _step.value;

                    // 如果record中存在需要过滤的值，且是新增操作，执行过滤，默认过滤$form
                    // eslint-disable-next-line
                    if (source[i][name] && source[i]._status === 'create') {
                      delete otherProps[name]; // eslint-disable-next-line

                      delete values[name];
                    }
                  }
                } catch (err) {
                  _iterator.e(err);
                } finally {
                  _iterator.f();
                }
              }

              list.push(_objectSpread(_objectSpread({}, otherProps), values));
            } else {
              // 捕获表单效验错误
              errList.push(err);
            }

            return err;
          });
        }

        if (source[i][treeChildrenAlias] && Array.isArray(source[i][treeChildrenAlias])) {
          fetchForm(source[i][treeChildrenAlias], list);
        }
      };

      for (var i = 0; i < source.length; i++) {
        _loop(i);
      }
    }
  };

  fetchForm(dataSource, paramsList);
  return errList.length > 0 ? [] : paramsList;
}